var async = require('async');
var bcrypt = require('bcrypt');
var queryString = require('querystring');
var url = require('url');

var models = require('./models');

function RequestLoginData(request, response){
	var user = false;
	if(request.session){
		user = request.session.user;
	}
	console.log('Requesting login data for '+user);
	if(!user){
		response.send({logged_in: false, user:false});
	}
	else{
		response.send({logged_in: true, user:user});
	}
}

function Register(request, response){
	var username = request.body.username;
	var password = request.body.password;
	models.user.findOne({name:username}, function(err, doc){
		console.log(doc);
		if(doc){
			response.send({success:false});
		}
		else{
			bcrypt.hash(password, 5, function(err, hashed_password) {
				doc = new models.user();
				doc.name = username;
				doc.password = hashed_password;
				doc.save();
				response.send({success:true});
			});
		}
	});
}

function Login(request, response){
	var username = request.body.username;
	var password = request.body.password;
	models.user.findOne({name:username}, function(err, doc){
		if(err){
			console.log(err);
			response.send({success:false, reason:'Unknown login error:'+err});
			return;
		}
		if(!doc){
			console.log('No such user found: '+username);
			response.send({success:false, reason:'No such user'});
			return;
		}
		
		bcrypt.compare(password, doc.password, function(err, same){
			if(err){
				console.log(err);
				response.send({success:false, reason:'Error comparing passwords'});
			}
			if(same){
                console.log("Login successful");
				request.session.user = doc.name;
				response.send({success:true});
			}
			else{
                console.log("Login failed");
				response.send({success:false, reason:'Incorrect password'});
			}
		});
	});
}

function Logout(request, response){
	request.session.destroy();
	response.send({success:true});
}

exports['request_login_data'] = RequestLoginData;
exports['login'] = Login;
exports['logout'] = Logout;
exports['register'] = Register;